package com.wthink.hzgj.util

import java.io.*
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException


object HashUtil {
    private val hexChar = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
    @Throws(InterruptedException::class)
    fun checkMd5(file: File, md5: String): Boolean {
        return md5 == getMd5(file)
    }

    @Throws(InterruptedException::class)
    fun getMd5(file: File): String {
        return getHash(file, "MD5")
    }

    @Throws(InterruptedException::class)
    private fun getHash(file: File, hashType: String): String {
        var fis: InputStream? = null
        try {
            fis = FileInputStream(file)//读取文件
            val buffer = ByteArray(1024 * 64)
            val md5 = MessageDigest.getInstance(hashType)
            while (fis.available() > 0) {
                val numRead = fis.read(buffer)
                md5.update(buffer, 0, numRead)
            }
            return toHexString(md5.digest())
        } catch (e: NoSuchAlgorithmException) {
            return ""
        } catch (e: FileNotFoundException) {
            return ""
        } catch (e: IOException) {
            return ""
        } finally {
            try {
                fis!!.close()
            } catch (e: Exception) {
            }
        }
    }

     fun toHexString(b: ByteArray): String {
        return b.asUByteArray().joinToString("") { it.toString(16).padStart(2, '0') }.toLowerCase()
    }


    fun hex2Str(hex: String): String? {
        val sb = StringBuilder()
        val split = hex.split(",").toTypedArray()
        for (str in split) {
            val i = str.toInt(16)
            sb.append(i.toChar())
        }
        return sb.toString()
    }
}